package com.kancy.publicapi.web.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.kancy.publicapi.web.filter.MDCFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * <p>
 * WebMvcConfiguration
 * </p>
 *
 * @author: kancy
 * @date: 2019/9/20 23:13
 **/
@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        setFastJsonConfig(fastJsonConfig);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        int index = 0;
        for (int i = 0; i < converters.size(); i++) {
            index = i;
            if (converters.get(i).getSupportedMediaTypes().contains(MediaType.APPLICATION_JSON)) {
                break;
            }
        }
        converters.add(index, fastConverter);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MDCFilter());
    }

    protected void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setCharset(Charset.forName("utf-8"));
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
    }

}
